<?php


class DistrictsController extends AppController {
    
    var $actsAs = array('Containable');
    
    var $name = 'Districts';
    
    
    var $components = array('RequestHandler','Security','Email');        
    
    
    function beforeFilter(){
        parent::beforeFilter();
        
            
        
        // ensure our ajax methods are posted
        $this->Security->requirePost('getnodes', 'reorder', 'reparent');
    }
    
    // Districts management 
    function admin_index() {
        
        $this->paginate['District'] = array('recursive' => -1,'conditions' => array(),'order'=>'lft asc');
        
        $cats = $this->paginate('District');
        
        $districts=array();
        
        foreach($cats as $c){
            $t=$c;
            $t['District']['parent']=$this->District->find('first',array('fields'=>array('name'),'recursive'=>-1,'conditions'=>array('id'=>$c['District']['parent_id'])));
            $districts[]=$t;
        }
        

        $this->set(compact('districts'));

    }
    
    
    
    // add Districts
    
    function admin_add($id=0) {
            
        if(!empty($this->data)):
            
            if(!$this->data["District"]["parent_id"])$this->data["District"]["parent_id"]=null;
            
            $this->data['District']['created'] = date('Y-m-d H:i:s');
            
            
            if($this->District->save($this->data)) :
                $this->Session->write('Success',true);
                $this->Session->setFlash('District Saved!');
                $this->redirect(array('controller' => 'districts', 'action' => 'index'));
                exit;
            endif;
        elseif($id):
        
            $this->District->id=$id;
            $this->data=$this->District->read();
            $this->set('id',$id);
        
        endif;
        
        
        
        $options = array(
            'conditions' => array('NOT' => array('id' => array(0,$id))),
            'recursive' => 0,
            'fields' => array('id','name'),
            'order' => array('lft' => 'ASC'),
        );
        
        $parents = $this->District->find('list', $options);
        
        $parents=array(0=>' -- (Root Location) --')+$parents;
        
        $this->set(compact('parents'));
        
        
        
        
    }
    
    
    // edit Districts
    
    function admin_edit($id=null) {
        
        if($id==null){
            $this->redirect($this->referer());
            exit;
        }
        
        $this->admin_add($id);
                
        $this->render('admin_add');
        
    }
    
    
    
    // delete District
    function admin_delete($id=null) {
    
    
        if($id==null){
            $this->redirect($this->referer());
            exit;
        }

        if($this->District->delete(array('District.id'=>$id))) :
            
            $this->Session->write('Success',true);
            $this->Session->setFlash('District deleted sucessfully');
            
        endif;
        
        
        $this->redirect($this->referer());
        exit;
    }
   

    
    function __clean($content) {
        $content = strip_tags($content);
        $content = preg_replace('/ style.*?=.*?(".*?"|\'.*?\')/', '', $content);
        $content = trim ($content);
        $content = $this->restoreTags($content);
        return $content;
    }
    
    
    
    // Original PHP code by Chirp Internet: www.chirp.com.au
    protected function restoreTags($input) {
        $opened = array();

        // loop through opened and closed tags in order
        if(preg_match_all("/<(\/?[a-z]+)>?/i", $input, $matches)) {
            foreach($matches[1] as $tag) {
                if(preg_match("/^[a-z]+$/i", $tag, $regs)) {
                    // a tag has been opened
                    if(strtolower($regs[0]) != 'br') $opened[] = $regs[0];
                } elseif(preg_match("/^\/([a-z]+)$/i", $tag, $regs)) {
                    // a tag has been closed
                    unset($opened[array_pop(array_keys($opened, $regs[1]))]);
                }
            }
        }

        // close tags that are still open
        if($opened) {
        $tagstoclose = array_reverse($opened);
        foreach($tagstoclose as $tag) $input .= "</$tag>";
    }

    return $input;
    }
    
    
    
    
    
    
    function admin_tree(){
        
    }
    
    
    
    
    
    
    function admin_getnodes() {
        
        
        $this->layout='admin/ajax_category';
        
        // retrieve the node id that Ext JS posts via ajax
        $parent = intval($this->params['form']['node']);
        
        // find all the nodes underneath the parent node defined above
        // the second parameter (true) means we only want direct children
        $nodes = $this->District->children($parent, true);
        
        // send the nodes to our view
        $this->set(compact('nodes'));
        
    }
    
    function admin_reorder() {
        
        // retrieve the node instructions from javascript
        // delta is the difference in position (1 = next node, -1 = previous node)
        
        $node = intval($this->params['form']['node']);
        $delta = intval($this->params['form']['delta']);
        
        if ($delta > 0) {
            $this->District->movedown($node, abs($delta));
        } elseif ($delta < 0) {
            $this->District->moveup($node, abs($delta));
        }
        
        
        
        // send success response
        exit('1');
        
    }
    
    function admin_reparent(){
        
        $node = intval($this->params['form']['node']);
        $parent = intval($this->params['form']['parent']);
        $position = intval($this->params['form']['position']);
        
        // save the employee node with the new parent id
        // this will move the employee node to the bottom of the parent list
        
        $this->District->id = $node;
        $this->District->saveField('parent_id', $parent);
        
        // If position == 0, then we move it straight to the top
        // otherwise we calculate the distance to move ($delta).
        // We have to check if $delta > 0 before moving due to a bug
        // in the tree behaviour (https://trac.cakephp.org/ticket/4037)
        
        if ($position == 0) {
            $this->District->moveup($node, true);
        } else {
            $count = $this->District->childcount($parent, true);
            $delta = $count-$position-1;
            if ($delta > 0) {
                $this->District->moveup($node, $delta);
            }
        }
        
        Cache::delete('front_menu', 'news');
        // send success response
        exit('1');
        
    } 
    
    
    function admin_rebuild_tree($parent, $left) {
       
        
        $right = $left + 1;   

        $options = array(
            'conditions' => array(
                'parent_id' => $parent,
            ),
            'fields' => array('id'),
            'order' => array('id' => 'ASC'),
            );
        
        $this->District->recursive = -1;
        $children = $this->District->find('all', $options);
        if($children) :
            foreach($children as $item) :
                $right = $this->admin_rebuild_tree($item['Category']['id'], $right);
            endforeach;
        endif;
        
        $this->District->updateAll(
            array(
                'lft' => $left,
                'rght' => $right,
            ),
            array(
                'id' => $parent,
            )
        );
        
        Cache::delete('front_menu', 'news');
                   
        return $right + 1;
    }
    
    
}
?>
